Nagios整合微信订阅号报警

        环境:rhel6.5 selinux 和 iptables 关闭。要求能上外网的(虚拟机亲测可用)

        以下是nagios服务与微信订阅号的整合过程,最终实现当服务或主机出现故障,自动调用微信报警。

        重点讲述如何配置微信公众平台私有接口,至于nagios服务的配置请大家参照nagios官方文档进行,此处不再赘述。(www.nagios.org)

1.下载微信公众平台私有接口

1
2
yum install -y git
git clone https://github.com/lealife/WeiXin-Private-API

2.修改微信公众平台私有接口代码,以配合nagios报警

1
2
3
cp -r WeiXin-Private-API /usr/local/nagios/libexec/weixin
chown -R nagios.nagios /usr/local/nagios/libexec/weixin
cd /usr/local/nagios/libexec/weixin

        修改config.php文件:

1
2
3
4
5
$G_CONFIG["weiXin"] = array(
'account' => '微信公众平台登录帐号',#填写你注册的微信订阅号的帐号和密码
'password' => '微信公众平台登录密码',

        修改test.php文件,只保留如下几行即可:

1
2
3
4
5
6
7
8
9
10
11
<?php
require "config.php";
require "include/WeiXin.php";
$weiXin = new WeiXin($G_CONFIG['weiXin']);
$testFakeId = "$argv[1]";#微信好友ID号,这里通过nagios传入
$msg = `cat /usr/local/nagios/var/nagios.msg`;#要发送的报警信息,由nagios传入
print_r($weiXin->send($testFakeId, "$msg"));#给微信好友发送信息

3.整合nagios和微信公共平台私有接口

增加微信报警选项: templates.cfg

        修改 /usr/local/nagios/etc/objects/templates.cfg

        在 define contact{…} 部分,将以下两行:

1
2
host_notification_commands notify-host-by-email
service_notification_commands notify-service-by-email

        改为:

1
2
host_notification_commands notify-host-by-email,notify-host-by-weixin
service_notification_commands notify-service-by-email,notify-service-by-weixin

增加调用命令: commands.cfg

        修改 /usr/local/nagios/etc/objects/commands.cfg

        在该文件的最后增加以下部分:

1
2
3
4
5
6
7
8
9
10
11
####notify-service-by-weixin
define command{
command_name notify-service-by-weixin
command_line /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" > /usr/local/nagios/var/nagios.msg && /usr/bin/php /usr/local/nagios/libexec/weixin/test.php $CONTACTADDRESS1$ &>/dev/null
}
####notify-host-by-weixin
define command{
command_name notify-host-by-weixin
command_line /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" > /usr/local/nagios/var/nagios.msg && /usr/bin/php /usr/local/nagios/libexec/weixin/test.php $CONTACTADDRESS1$ &>/dev/null
}

修改联系人选项: contact.cfg

        修改 /usr/local/nagios/etc/objects/contact.cfg

        在 define contact{…} 部分增加如下一行

1
address 11206***#微信好友ID,登录微信公众平台网页版,在用户管理中点击你要发微信的好友,此时在地址上显示的fakeid就是微信好友的ID。

重载nagios配置

1
service nagios reload